import React, { useEffect, useState } from 'react';
import { useRequest } from '@umijs/hooks'
import { useSelector, useDispatch } from 'umi';
import { Modal, Form, message, Button, Layout } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

import { query, add, update, del } from './server';
import { CustomerEditModalState, CustomerEditState } from './data.d';
import useModal from '@/hooks/useModal';
import { ConnectState } from '@/models/connect.d';
import CustomerTable from './CustomerTable';
import EditModal from './EditModal';
import SecondTitle from '@/components/SecondTitle'

const { Content } = Layout;


const NormalTable: React.FC<any> = (props: any) => {

  // const [customerModel, setcustomerModel] = useState<CustomerTableState>(initcustomerModel);
  const { route } = props;

  const dispatch = useDispatch()
  const customerModel = useSelector(
    (state: ConnectState) => state.normalTable,
  );


  const [currentItem, setCurrentItem] = useState<any>({});
  const { type, visible, toggle, setTypeWithVisible } = useModal();


  const queryCustomerRequest = useRequest(query, {
    manual: true,
    cacheKey: 'customer',
    onSuccess: (response, params) => {
      // console.log(response, params)
      if (response && response.status === 200) {
        const { q, desc } = params[0];
        const filter = {
          ...customerModel.filter,
          q,
          desc
        }
        const { customers, page, size, total } = response.data.data;
        dispatch({
          type: 'normalTable/saveData',
          payload: {
            filter,
            data: customers,
            page: {
              page, size
            },
            total
          }
        })
      }
    }
  })

  const updateCustomerRequest = useRequest(update, {
    manual: true,
    fetchKey: (params, onlySwitch?) => {
      // console.log(params);
      return params.id;
    },
    onSuccess: (response, params) => {
      // console.log(response, params)
      if (response && response.status === 200) {
        message.success(response.data.message)
        // queryList();
        queryList();
        if (!params[1]) {
          toggle();
        }
      }
    }
  })

  const addCustomerRequest = useRequest(add, {
    manual: true,
    onSuccess: (response, params) => {
      // console.log(response, params)
      if (response && response.status === 200) {
        message.success(response.data.message)
        queryList();
        toggle();
      }
    }
  })
  const delCustomerRequest = useRequest(del, {
    manual: true,
    onSuccess: (response, params) => {
      // console.log(response, params)
      if (response && response.status === 200) {
        message.success(response.data.message)
        queryList();
      }
    }
  })

  useEffect(() => {
    queryList()
    return (() => {
      dispatch({ type: 'normalTable/clear' })
    })
  }, [])

  // 获取表格数据
  const queryList = async (payload?: any) => {
    const params = {
      ...customerModel.filter,
      ...customerModel.page,
      ...payload,
    }
    queryCustomerRequest.run(params)
  }

  // 页码
  function onPageChange(page: number, size: number) {
    queryList({ page, size });
  }

  // 编辑(新增)表单
  const editModalProps: CustomerEditModalState = {
    visible: visible,
    currentItem: type === 'add' ? {} : currentItem,
    confirmLoading: updateCustomerRequest.loading || addCustomerRequest.loading,
    type: type,
    onEdit: (values: CustomerEditState) => {
      type === 'add' ? addCustomerRequest.run(values) : updateCustomerRequest.run(values);
    },
    onCancel: () => {
      toggle()
    }
  }

  // 表格props
  const tableProps = {
    dataSource: customerModel.data,
    loading: queryCustomerRequest.loading,
    pagination: {
      pageSize: customerModel.page.size,
      current: customerModel.page.page,
      total: customerModel.total,
      onChange: onPageChange,
      onShowSizeChange: onPageChange,
      showQuickJumper: true,
      showSizeChanger: true,
    },
    onEdit: (record: any) => {
      setCurrentItem(record);
      setTypeWithVisible('update')
    },
    onDel: (record: any) => {
      Modal.confirm({
        title: '确认删除本条数据',
        icon: <ExclamationCircleOutlined />,
        okText: '确认',
        onOk: () => {
          delCustomerRequest.run(record)
        },
        cancelText: '取消',
      });
    },
    onRowClick: (record: any) => {
      // console.log('row-click', record);
    },
    onChangeWorkStatus: (record: any) => {
      updateCustomerRequest.run(record, true)
    }
  }

  return (
    <Layout>
      <SecondTitle {...{ title: route.name }}></SecondTitle>

      <div className="btn-content" style={{ padding: '20px 0', background: '#fff' }}>
        <Button type="primary" onClick={() => { setTypeWithVisible('add') }}>新增客户端</Button>
        <Button type="primary" >{currentItem.name || '测试'}</Button>
      </div>
      <CustomerTable {...tableProps}></CustomerTable>


      <EditModal {...editModalProps}></EditModal>
    </Layout>
  )
}

export default NormalTable;